<?php

namespace app\common\model;


class ShopDeliveryModel extends BaseModel
{
    protected $name = 'shop_delivery'; //定义栏目表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    protected $type = [
        'delivery_weight_calc'    => 'array',
        'delivery_promotion_rule' => 'array',
    ];

    /*读取器*/
    public function getDeliveryTypeTextAttr($value, $data)
    {
        $status = [0 => '免费', 1 => '固定运费', 2 => '按重量计算'];
        return $status[$data['delivery_type']];
    }

    public function getIsDefaultTextAttr($value, $data)
    {
        $status = [0 => '非默认', 1 => '默认'];
        return $status[$data['is_default']];
    }

    public function getStatusTextAttr($value, $data)
    {
        $status = [0 => '禁用', 1 => '启用'];
        return $status[$data['status']];
    }

    /**
     * 根据购买商品列表计算运费
     * @param array $skuIds 商品Sku列表['sku_id'=>num]
     * @param integer $deliveryId :运费模板id
     * @param float $orderPrice :订单总价
     * @return float 最后运费计算价格
     */
    public function calculateFreight($skuIds, $deliveryId, $orderPrice)
    {
        $fright        = 0;
        $deliveryModel = new ShopDeliveryModel();
        $deliveryInfo  = $deliveryModel->get($deliveryId);
        switch ($deliveryInfo['delivery_type']) {
            case 0:
                $fright = 0;
                break;
            case 1:
                $fright = $deliveryInfo['delivery_money'];
                break;
            case 2:
                $skuModel             = new ShopGoodsSkuModel();
                $delivery_weight_calc = $deliveryInfo['delivery_weight_calc'];
                $sku                  = $skuModel->where('sku_id', 'in', array_keys($skuIds))->column('goods_weight', 'sku_id'); //总重量
                $skuWeight            = 0;
                foreach ($sku as $item => $value) {
                    $skuWeight += $value * $skuIds[$item];
                }
                $fright = $delivery_weight_calc['first_fright'];
                if ($skuWeight - $delivery_weight_calc['first_weight'] > 0) {
                    $fright += ceil(($skuWeight - $delivery_weight_calc['first_weight']) / $delivery_weight_calc['second_weight']) * $delivery_weight_calc['second_fright'];
                }
                break;
        }
        $delivery_promotion_rule = $deliveryInfo['delivery_promotion_rule'];
        if ($deliveryInfo['delivery_type'] !== 0) {
            switch ($deliveryInfo['delivery_promotion_type']) {
                case 1:
                    $fright = $orderPrice >= $delivery_promotion_rule['price'] ? 0 : $fright - 0;
                    break;
                case 2:
                    $fright = $orderPrice >= $delivery_promotion_rule['price'] ? $fright - $delivery_promotion_rule['fright'] : $fright;
                    break;
            }
        }
        return $fright;
    }

}